import { ModeTypeConst } from '../../constant';
import { QuickActionModeOption } from '../../interface';

/**
 * 操作栏模式
 *
 * @author chitanda
 * @date 2022-06-28 14:06:02
 * @export
 * @class QuickActionMode
 */
export class QuickActionMode {
  readonly opts: QuickActionModeOption;

  get isDefault(): boolean {
    return this.opts.type === ModeTypeConst.DEFAULT;
  }

  constructor(options: QuickActionModeOption) {
    if (options.type !== ModeTypeConst.DEFAULT && !options.command && (!options.tag || options.tag === '')) {
      throw new Error('QuickActionModeOption tag must not be empty');
    }
    this.opts = { ...options };
    this.init();
  }

  protected init(): void {
    if (!this.opts.command && this.opts.keyboards) {
      Mousetrap.bind(this.opts.keyboards, async e => {
        if (e) {
          if (e.preventDefault) {
            e.preventDefault();
          }
          if (e.stopPropagation) {
            e.stopPropagation();
          }
        }
        this.open();
      });
    }
  }

  async open(): Promise<void> {
    const { provider } = this.opts;
    await window.quickAction.open(provider);
  }

  /**
   * 销毁
   *
   * @author chitanda
   * @date 2022-06-28 14:06:56
   */
  destroyed(): void {
    if (!this.opts.command && this.opts.keyboards) {
      Mousetrap.unbind(this.opts.keyboards);
    }
  }
}
